const Sequelize = require("sequelize")
const {
  Customer,
  Goods,
  GoodsAttr,
  GoodsAttrValue,
  GoodsAttrResult,
  GoodsAttrConfig,
  StoreHouse,
  Order,
  OrderGoods,
} = require("../model")
const moment = require("moment")
const utils = require("../utils/index.js")
// const { sqlConn } = require("../db/connect")

// 获取用户所有购买过的商品 最近一次
const customerIndex = async params => {
  const { store_id } = params;
  const sql = `SELECT o.id as 'order_id', o.order_no, o.customer_id, og.sku_id, ga.goods_name, ga.sku, og.goods_price, og.discount,
  og.discount_price, og.goods_num, og.remarks, max(DATE_FORMAT(og.create_time, '%Y-%m-%d %H:%i:%S')) as 'create_time'
  from sp_store_order as o
  LEFT JOIN sp_store_order_goods as og on og.order_id = o.id
  LEFT JOIN sp_store_goods_attr_value as ga on ga.id = og.sku_id
  where o.store_id = ${store_id}
  GROUP BY og.sku_id
  ORDER BY o.customer_id ASC, og.create_time DESC;`
  let result = null
  return new Promise((resolve,reject) => {
    sqlConn(sql, [], (err, res) => {
      console.log("customerIndex--sqlConn--err: %s==", JSON.stringify(err))
      console.log("customerIndex--sqlConn--res: %s==", JSON.stringify(res))
      if (err) {
        result = err;
      } else {
        result = res;
      }
      resolve(result)
    })
  })
}

const getCustomerDetail = async id => {
  if (!id) return '';
}

// 用户 订单  1-n
const OrderHasMany = Customer.hasMany(Order, {
  // foreignKey: "goods_id",
  foreignKey: "customer_id",
  constraints: false,
  as: "orders",
  order: ["sort", "ASC"]
})
// 订单 商品 1-n
const OrderGoodsHasMany = Order.hasMany(OrderGoods, {
  // targetKey: "id",
  foreignKey: "order_id",
  constraints: false,
  as: "orderGoods",
  order: ["sort", "ASC"]
})
// // 商品 规格 1-n
// const GoodsAttrHasOne = OrderGoods.hasMany(GoodsAttrValue, {
//   foreignKey: 'sku_id',
//   targetKey: 'id',
//   constraints: false,
//   as: "attrValue"
// })

const customerIndex2 = async params => {

  const { store_id } = params;
  
  try {
    const list = await Customer.findAll({
      where: { store_id },
      include: [
        {
          association: OrderGoodsHasMany,
          include: [
            {
              association: OrderGoodsHasMany,
              include: [
                {
                  association: GoodsAttrHasOne,
                }
              ]
            }
          ]
        }
      ]
    })
    console.log("customerIndex--list: %s==", JSON.stringify(list));
    const count = list.length || 0
    return { count, rows: list };
  } catch(err) {
    console.log("customerIndex--err: %s==", JSON.stringify(err));
    return { code: 500 }
  }
}

const updateCustomerConfig = async params => {
  console.log("updateCustomerConfig--params: %s==", JSON.stringify(params))
  const { order, customer } = params
  try {
    // 获取用户信息
    if (!customer) {
      customer = await Customer.findOne({
        where: { id: order.customer_id }
      })
    }
    console.log("Customer.findOne--customer: %s==", JSON.stringify(customer))
    let customerConfig = customer.config
      ? JSON.parse(customer.config)
      : { goods_record: {} }
    console.log(
      "Customer.findOne--customerConfig: %s==",
      JSON.stringify(customerConfig)
    )
    let goods_record = customerConfig.goods_record || {}
    console.log(
      "updateCustomerConfig--goods_record: %s==",
      JSON.stringify(goods_record)
    )
    const orderDate = new Date(order.create_time).getTime()
    // 订单商品数据
    let isUpdata = false
    const goods_list = order.goods_list
    // 遍历订单商品列表
    goods_list.forEach(async (goods, index) => {
      if (goods_record[goods.goods_id]) {
        // 客户第二次或以上下单 获取历史记录
        const goodsSkuList = goods_record[goods.goods_id]
        if (goodsSkuList.length) {
          // 遍历历史记录数据
          for (let i = goodsSkuList.length - 1; i >= 0; i--) {
            // 获取
            const goodsIndex = goodsSkuList.findIndex(
              d => d.goods_sku === goods.goods_sku
            )
            console.log("goodsIndex--:%s==", goodsIndex)

            // 判断是否有记录
            if (goodsIndex >= 0) {
              // 获取记录更新时间
              const update_time = new Date(
                goodsSkuList[goodsIndex].update_time
              ).getTime()
              // discount < 0.1 认为是赠送不更新记录，比较记录更新时间与当前订单时间
              if (Number(goods.discount) > 0.1 && update_time < orderDate) {
                goodsSkuList[goodsIndex] = {
                  goods_id: goods.goods_id,
                  goods_name: goods.goods_name,
                  goods_price: goods.goods_price,
                  goods_sku_id: goods.id,
                  goods_sku: goods.goods_sku,
                  update_time: order.create_time
                }
                isUpdata = true
              } else {
                // 1.商品折扣小于 0.1 认为是赠送 不更新记录信息
                // 2.记录更新时间小于当前订单时间 不更新记录信息
                console.log(
                  "goods.goods_name: %s--goods.goods_sku: %s--discount: %s--diffTime: %s==",
                  goods.goods_name,
                  goods.goods_sku,
                  Number(goods.discount),
                  update_time - orderDate
                )
              }
            } else {
              goodsSkuList.push({
                goods_id: goods.goods_id,
                goods_name: goods.goods_name,
                goods_price: goods.goods_price,
                goods_sku_id: goods.id,
                goods_sku: goods.goods_sku,
                update_time: order.create_time
              })
              isUpdata = true
            }
          }
        } else {
          console.log("goodsSkuList.length--%s==", goods.goods_id)
          goods_record[goods.goods_id] = [
            {
              goods_id: goods.goods_id,
              goods_name: goods.goods_name,
              goods_price: goods.goods_price,
              goods_sku_id: goods.id,
              goods_sku: goods.goods_sku,
              update_time: order.create_time
            }
          ]
          isUpdata = true
        }
      } else {
        // 客户第一次下单
        console.log("不存在--%s==", goods.goods_id)
        goods_record[goods.goods_id] = [
          {
            goods_id: goods.goods_id,
            goods_name: goods.goods_name,
            goods_price: goods.goods_price,
            goods_sku_id: goods.id,
            goods_sku: goods.goods_sku,
            update_time: order.create_time
          }
        ]
        isUpdata = true
      }
      console.log(
        "Customer.update-1--isUpdata: %s--goods_record: %s==",
        isUpdata,
        index
      )
      if (index === goods_list.length - 1 && isUpdata) {
        customerConfig.goods_record = goods_record
        customer.config = JSON.stringify(customerConfig)
        const res = await customer.update({
          config: JSON.stringify(customerConfig),
          where: { id: order.customer_id }
        })
        console.log("Customer.update--customer: %s==", JSON.stringify(res))
      }
    })
    // console.log(
    //   "Customer.update--isUpdata: %s--goods_record: %s==",
    //   isUpdata,
    //   JSON.stringify(goods_record)
    // )
  } catch (err) {
    console.log("Customer.findByPk--err: %s==", err)
  }
}

module.exports = {
  customerIndex,
  updateCustomerConfig
}
